package com.atmilan.quartz.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.atmilan.quartz.utils.product.ColtortiProductUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.atmilan.quartz.constant.Constants;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.SyncStatusEnum;
import com.atmilan.quartz.model.dto.coltorti.ColtortiProductResDTO;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.coltorti.ColtortiProduct;
import com.atmilan.quartz.model.entity.crmeb.StoreProduct;
import com.atmilan.quartz.model.entity.crmeb.SystemConfig;
import com.atmilan.quartz.service.IColtortiProductService;
import com.atmilan.quartz.service.IColtortiSyncService;
import com.atmilan.quartz.service.IStoreProductAttrService;
import com.atmilan.quartz.service.IStoreProductAttrValueService;
import com.atmilan.quartz.service.IStoreProductService;
import com.atmilan.quartz.service.ISystemConfigService;
import com.atmilan.quartz.utils.RedisUtil;
import com.atmilan.quartz.utils.source.SourceColtortiProductUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Howe Hsiang
 */
@Slf4j
@Service
public class ColtortiSyncServiceImpl implements IColtortiSyncService {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    ISystemConfigService systemConfigService;
    @Autowired
    IColtortiProductService coltortiProductService;
    @Autowired
    IStoreProductService storeProductService;
    @Autowired
    IStoreProductAttrService storeProductAttrService;
    @Autowired
    IStoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    SourceColtortiProductUtil sourceColtortiProductUtil;
    @Autowired
    ColtortiProductUtil coltortiProductUtil;

    /**
     * 获取远程数据并保存到数据源
     */
    @Override
    public Boolean syncProduct() {
        // 数据清空
        coltortiProductService.deleteAll();

        int pageNo = 1;
        int pageCount = 1;
        long millis = System.currentTimeMillis();
        while(pageNo <= pageCount) {
            try {
                List<ColtortiProductResDTO> goodsList = coltortiProductUtil.selectColtortiPage();
                if(CollectionUtils.isEmpty(goodsList)) {
                    log.info("--------------- coltorti获取商品接口请求失败 ---------------");
                    continue;
                }
                log.info("coltorti获取商品行数: {}",goodsList.size());
                
                // 商品保存
                saveGoods(goodsList);
                
            } catch (Exception e) {
                e.printStackTrace();
                log.error("com.atmilan.quartz.service.impl.ColtortiSyncServiceImpl.syncProduct error:",e);
            }
            log.info("--------------- coltorti远程抓取数据, 第: {} 页,  总共: {} 页, 总耗时: {} 分  ---------------", pageNo, pageCount, (int)((System.currentTimeMillis() - millis) / 1000 / 60));
            pageNo++;
        }
        pushProduct();
    
        return true;
    }
    
    // 商品源数据保存
    private void saveGoods(List<ColtortiProductResDTO> goodsList) {
        // 商品数据
        List<ColtortiProduct> goodsEntity = new ArrayList<>();
        for(ColtortiProductResDTO goods : goodsList) {
            ColtortiProduct productEntity = new ColtortiProduct();
            BeanUtils.copyProperties(goods, productEntity);
            goodsEntity.add(productEntity);
        }

        try {
            coltortiProductService.saveBatch(goodsEntity);
        }catch (Exception e) {
            log.error("coltorti数据存储异常: ",e);

        }
    }

    @Override
    public Boolean pushProduct() {
        try {
            // 当次更新少于5千条, 则不更新, 并且重新拉取
            int count = coltortiProductService.count();
            if(5000 > count) {
                systemConfigService.update(Wrappers.<SystemConfig>lambdaUpdate()
                        .eq(SystemConfig :: getName, Constants.COLTORTI_SYNC_STATUS)
                        .set(SystemConfig :: getFormId, SyncStatusEnum.PUSH)
                        .set(SystemConfig :: getUpdateTime, new Date())
                        );
                log.info("--------------- coltorti商品源数据, 少于规定条数, 不进行下发, 总条数为: {} ---------------", count);
                return false;
            }
            
            // 将所有coltorti商品更新状态置为未更新
            storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                    .eq(StoreProduct :: getIsEurope, ProductTypeEnum.COLTORTI.getCode())
                    .set(StoreProduct :: getUpdateFlag, false)
                    );
            
            // 商品更新操作
            int pageNo = 1;
            int pageSize = 100;
            int maxPage = (count + pageSize - 1) / pageSize;
            log.info("--------------- 开始分页查询coltorti商品源数据, 本次更新总条数为: {} ---------------", count);

            long millis = System.currentTimeMillis();
            while (pageNo <= maxPage) {
                try {
                    PageHelper.startPage(pageNo, pageSize);
                    List<ColtortiProduct> coltortiProducts = coltortiProductService.list();
                    PageInfo<ColtortiProduct> pageInfo = PageInfo.of(coltortiProducts);
                    List<ColtortiProduct> products = pageInfo.getList();
                    buildProduct(products);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                log.info("--------------- coltorti下发商品到数据库, 当前页数: {}, 总页数: {}, 耗时: {} 分 ---------------", pageNo, maxPage, (int)((System.currentTimeMillis() - millis) / 1000 / 60));
                pageNo++;
            }
            // 图搜删除
            storeProductService.delSeachImage(ProductTypeEnum.COLTORTI);
            // 查询是否异常下放(新更新商品数量小于500)
            int newCount = storeProductService.count(Wrappers.<StoreProduct>lambdaQuery()
            		.eq(StoreProduct::getIsEurope, ProductTypeEnum.COLTORTI.getCode())
            		.eq(StoreProduct::getUpdateFlag, true)
            		.eq(StoreProduct :: getIsShow, true)
            		);
            if(500 > newCount) {
            	log.info("--------------- coltorti下发商品异常, {} 数量不对!!!! ---------------", newCount);
                return true;
            }
            // 下架所有未更新数据
            storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                    .eq(StoreProduct::getIsEurope, ProductTypeEnum.COLTORTI.getCode())
                    .eq(StoreProduct::getUpdateFlag, false)
                    .eq(StoreProduct :: getIsShow, true)
                    .eq(StoreProduct :: getIsDel, false)
                    .set(StoreProduct::getIsShow, false)
                    .set(StoreProduct::getStock, 0)
                    .set(StoreProduct::getLastPushTime, new Date())
                    .set(StoreProduct::getIsTusou, false)
                    );
            // 下架所有sku库存
            storeProductService.downloadSku(ProductTypeEnum.COLTORTI.getCode());

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return false;
    }

    /**
     * 商品构建处理
     * @Description:  
     * @author daigb 
     * @param @param products
     * @return void
     * @throws
     */
    private void buildProduct(List<ColtortiProduct> products) {
        try {
            for (ColtortiProduct product : products) {
                if(StringUtils.isBlank(product.getSize())){
                    continue;
                }
                int stock = product.getQty();
                if (0 >= stock) {
                    continue;
                }

                // 构建实体
                StoreProductCrmebRequest storeProductCrmebRequest = sourceColtortiProductUtil.buildColtortiProduct(product);
                if(null == storeProductCrmebRequest) {
                	log.info("--------------- coltorti下发异常, 商品无数据 ! ---------------");
                    continue;
                }
                // 数据保存
                StoreProduct storeProduct = storeProductService.getByBarCode(storeProductCrmebRequest.getBarCode(), storeProductCrmebRequest.getSuppliersId(), storeProductCrmebRequest.getKeyword());
                storeProductService.saveOtProduct(storeProductCrmebRequest, storeProduct, stock);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}
